package cn.ncu.controller;

import cn.ncu.entity.Article;
import cn.ncu.service.ArticleService;
import cn.ncu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("article")
@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 分页查询文章
     * @param authorid
     * @param currentPage
     * @param rows
     * @return
     */
    @GetMapping("findByPage")
    public Result findByPage(String authorid, Integer currentPage, Integer rows) {
        Result result = new Result();
        List<Article> articles = articleService.findByPage(authorid, currentPage, rows);
        if (articles != null) {
            Integer total = articleService.findTotal(authorid);
            result.setFlag(true).setArticles(articles).setTotal(total);
        } else {
            result.setMessage("分页查询失败！");
        }
        return result;
    }

    @GetMapping(value = {"articleDetails","updateArticle"})
    public Result articleDetails(String articleid){
        Result result = new Result();
        Article article = articleService.findArticleByArticleid(articleid);
        if(article!=null){
            result.setArticle(article).setFlag(true);
        }else {
            result.setMessage("啊哦，他（她）还没有任何文章啊！");
        }
        return result;
    }

    @PostMapping("saveArticle")
    public Result saveArticle(@RequestBody Article article){
        Result result = new Result();
        Article article1 = articleService.findArticleByArticleid(article.getAid());
        if(article1 != null){
            article.setModifytime(new Date());
            try {
                articleService.updateArticle(article);
                result.setFlag(true);
            } catch (Exception e) {
                result.setMessage("更新失败，请稍后重试！");
            }
        }else {
            try {
                articleService.saveArticle(article);
                result.setFlag(true);
            } catch (Exception e) {
                result.setMessage("保存失败，请稍后重试！");
            }
        }
        return result;
    }

    @GetMapping("deleteArticle")
    public Result deleteById(String articleid){
        Result result = new Result();
        try {
            articleService.deleteArticle(articleid);
            result.setFlag(true);
        } catch (Exception e) {
            result.setMessage("删除失败，请稍后重试");
        }
        return result;
    }

}
